using System;
using QAssetBundle;
using UnityEngine;
using QFramework;

namespace ProjectSurvival
{
    public partial class Enemy : ViewController, IEnemy
    {
        [SerializeField] private bool isTreasure = false;
        public float moveSpeed = 1f;
        public float hp = 3;
        public Color DissolveColor = Color.red;

        void Start()
        {
            // Code Here
            EnemyGenerator.EnemyCount.Value++;
        }

        private void OnDestroy()
        {
            EnemyGenerator.EnemyCount.Value--;
        }

        private void FixedUpdate()
        {
            if (!_ignoreHurt)
            {
                if (Player.Instance)
                {
                    var direction = (Player.Instance.transform.position - transform.position).normalized;
                    SelfRigidbody2D.velocity = direction * moveSpeed;
                }
                else
                {
                    SelfRigidbody2D.velocity = Vector2.zero;
                }
            }
        }

        private void Update()
        {
            if (hp <= 0)
            {
                Global.GeneratePowerUp(transform,isTreasure);
                FxController.instance.Play(Sprite, DissolveColor);
                AudioKit.PlaySound(Enemy_die_mp3.Enemy_die);
                gameObject.DestroySelfGracefully();
            }
        }

        private bool _ignoreHurt = false;

        public void Hurt(float hurtValue, bool force = false,bool critical = false)
        {
            if (_ignoreHurt && !force)
            {
                return;
            }
            _ignoreHurt = true;
            SelfRigidbody2D.velocity = Vector2.zero;
            
            FloatingTextController.PlayText(transform.position + Vector3.up * 0.5f, hurtValue.ToString("0"),critical);
            
            Sprite.color = Color.red;
            AudioKit.PlaySound(Hit_wav.HIt);
            ActionKit.Delay(0.2f, () =>
            {
                hp -= hurtValue;
                Sprite.color = Color.white;
                _ignoreHurt = false;
            }).Start(this);
        }

        public void SetSpeedScale(float hpScaleValue)
        {
            this.hp *= hpScaleValue;
        }

        public void SetHpScale(float speedScaleValue)
        {
            this.moveSpeed *= speedScaleValue;
        }
    }
}